package com.our.base.easylog.logback.appender;

import java.util.Date;

import org.springframework.stereotype.Component;

import com.our.base.easylog.config.cache.CachePool;
import com.our.base.easylog.entity.LogInfo;

import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;
import ch.qos.logback.core.Layout;
import lombok.Getter;

/**
 * 日志推送Appender
 *
 * @author Alice
 * @date 2023/11/29
 **/
@Component
public class PushLogAppender extends AppenderBase<ILoggingEvent> {

    CachePool cachePool;

    @Getter
    private Layout<ILoggingEvent> layout;

    @Override
    public void start() {
        super.start();
        cachePool = CachePool.getCachePool();
    }

    @Override
    protected void append(ILoggingEvent eventLog) {
        // 拿到日志
        String log = layout.doLayout(eventLog);
        eventLog.prepareForDeferredProcessing();
        // 过滤掉框架本身的日志
        if ("easy-log".equals(eventLog.getLoggerName())) {
            return;
        }

        LogInfo logInfo = new LogInfo();
        logInfo.setLog(log);
        logInfo.setLogTime(new Date());
        logInfo.setMdcInfo(eventLog.getMDCPropertyMap());

        cachePool.writeOneData(logInfo);
    }

    public void setLayout(Layout<ILoggingEvent> layout) {
        this.layout = layout;
    }
}

